package com.cs171.market.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cs171.market.Repository.CommentRepository;
import com.cs171.market.Repository.GoodRepository;
import com.cs171.market.entity.Comment;
import com.cs171.market.entity.Good;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangyifei
 * @version 1.0
 * @date 2020/6/20 19:29
 */

@CrossOrigin
@RestController
public class SearchController {
    @Autowired
    private GoodRepository goodRepository;
    @Autowired
    private CommentRepository commentRepository;

    @GetMapping("/search/{keyword}")
    public Object searchGood(@PathVariable("keyword") String kw) throws UnsupportedEncodingException {
        JSONObject result = jsonhead();
        List<Map<String, Object>> goodMap = goodRepository.searchJsonAboutGoods();
        List<Map<String, Object>> commentMap = commentRepository.cntGoodCandSumC();
        List<Map<String, Object>> goods = new ArrayList<>();

        for(Map<String, Object>g : goodMap){
            String name = (String) g.get("title");
            Integer id = (Integer) g.get("id");
            Map<String, Object> newMap = new HashMap<>(g);
            // 搜索匹配kw
            //String kw_cn = new String(kw.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);;
            if(name.contains(kw) || kw.contains(name)){
                for(Map<String, Object>c : commentMap){
                    Integer gid = (Integer) c.get("gid");
                    if(id.equals(gid)){
                        newMap.put("commentCount",c.get("commentCount"));
                        newMap.put("positiveCount",c.get("positiveCount"));
                    }
                }
                goods.add(newMap);
            }
        }
        JSONArray goodJson = (JSONArray) JSON.toJSON(goods);
        JSONObject searchJson = new JSONObject();
        searchJson.put("searchList", goodJson);
        result.put("data", searchJson);
        return result;
    }

    /**
     * 重构代码，相似的Json Head
     * @return JsonObject
     */
    private JSONObject jsonhead(){
        JSONObject pAll = new JSONObject();
        pAll.put("success", "true");
        return pAll;
    }
}
